<template>
  <view class="app-image-upload">
    <!-- 标题和说明 -->
    <view class="upload-header">
      <view class="header-title">
        <u-icon name="photo" color="#409eff" size="16"></u-icon>
        <text class="title-text">{{ title }}</text>
        <text v-if="required" class="required">*</text>
      </view>
      <view v-if="tip" class="upload-tip">{{ tip }}</view>
    </view>

    <!-- 图片上传区域 -->
    <view class="image-upload-area">
      <view class="image-grid">
        <!-- 已上传的图片 -->
        <view 
          v-for="(image, index) in imageList" 
          :key="index"
          class="image-item"
        >
          <image 
            :src="image.url || image" 
            mode="aspectFill" 
            class="uploaded-image"
            @click="previewImage(index)"
          ></image>
          <view class="delete-btn" @click="removeImage(index)">
            <u-icon name="close" color="#fff" size="12"></u-icon>
          </view>
          <!-- 上传进度指示器 -->
          <view v-if="image.uploading" class="upload-progress">
            <u-loading-icon mode="circle" size="20"></u-loading-icon>
          </view>
        </view>

        <!-- 添加图片按钮 -->
        <view 
          v-if="imageList.length < maxCount"
          class="upload-btn"
          @click="chooseImage"
        >
          <u-icon name="plus" color="#999" size="24"></u-icon>
          <text class="upload-text">{{ addButtonText }}</text>
        </view>
      </view>
    </view>

    <!-- 错误提示 -->
    <view v-if="errorMessage" class="error-message">
      <u-icon name="error-circle" color="#f56c6c" size="14"></u-icon>
      <text class="error-text">{{ errorMessage }}</text>
    </view>
  </view>
</template>

<script>
import { ref, watch } from 'vue'
import { repairApi } from '@/api/repair'

export default {
  name: 'AppImageUpload',
  
  props: {
    // 图片列表
    modelValue: {
      type: Array,
      default: () => []
    },
    // 标题
    title: {
      type: String,
      default: '图片上传'
    },
    // 提示文字
    tip: {
      type: String,
      default: '请上传图片，支持jpg、jpeg、png、gif、bmp、webp格式'
    },
    // 最大上传数量
    maxCount: {
      type: Number,
      default: 9
    },
    // 是否必填
    required: {
      type: Boolean,
      default: false
    },
    // 添加按钮文字
    addButtonText: {
      type: String,
      default: '添加图片'
    },
    // 图片大小限制（MB）
    maxSize: {
      type: Number,
      default: 10
    },
    // 允许的图片类型
    allowedTypes: {
      type: Array,
      default: () => ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
    },
    // 是否支持多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 是否支持拍照
    allowCamera: {
      type: Boolean,
      default: true
    },
    // 是否支持相册
    allowAlbum: {
      type: Boolean,
      default: true
    },
    // 是否自动上传
    autoUpload: {
      type: Boolean,
      default: true
    }
  },

  emits: ['update:modelValue', 'change', 'success', 'error', 'remove', 'preview'],

  setup(props, { emit }) {
    const imageList = ref([...props.modelValue])
    const errorMessage = ref('')

    // 数组比较函数
    const arraysEqual = (a, b) => {
      if (a === b) return true
      if (a == null || b == null) return false
      if (a.length !== b.length) return false
      for (let i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) return false
      }
      return true
    }

    // 监听modelValue变化
    watch(() => props.modelValue, (newVal, oldVal) => {
      // 比较数组内容，避免不必要的更新
      if (!arraysEqual(newVal, oldVal)) {
        imageList.value = [...newVal]
      }
    }, { deep: true })

    // 监听imageList变化，同步到父组件
    watch(imageList, (newVal, oldVal) => {
      console.log('AppImageUpload - imageList变化:', { newVal, oldVal })
      console.log('AppImageUpload - 触发update:modelValue事件:', newVal)
      // 直接触发更新，不进行数组比较
      emit('update:modelValue', [...newVal])
      emit('change', [...newVal])
    }, { deep: true })

    // 上传图片到服务器
    const uploadImage = async (filePath) => {
      try {
        console.log('开始上传图片:', filePath)
        
        // 创建临时图片对象，标记为上传中
        const tempImage = {
          url: filePath,
          uploading: true,
          error: false
        }
        
        // 添加到图片列表
        imageList.value.push(tempImage)
        
        // 调用上传API
        const result = await repairApi.uploadFile(filePath, 'REPAIR_IMAGE', 'APP')
        
        console.log('图片上传结果:', result)
        
        if (result && result.code === 200 && result.data) {
          // 上传成功，更新图片信息
          const uploadedImage = {
            id: result.data.id || Date.now(),
            url: result.data.fileUrl, // 根据API文档，字段名是fileUrl
            fileName: result.data.fileName,
            fileSize: result.data.fileSize,
            fileType: result.data.fileType,
            fileExtension: result.data.fileExtension,
            uploadType: result.data.uploadType,
            uploadSource: result.data.uploadSource,
            uploading: false,
            error: false
          }
          
          // 更新图片列表中的对应项
          const index = imageList.value.findIndex(img => img.url === filePath)
          if (index !== -1) {
            // 使用Vue的响应式更新方法
            imageList.value.splice(index, 1, uploadedImage)
          }
          
          console.log('图片上传成功:', uploadedImage)
          console.log('更新后的imageList:', imageList.value)
          emit('success', [uploadedImage])
          clearError()
          
          return uploadedImage
        } else {
          throw new Error(result?.message || '上传失败')
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        
        // 标记上传失败
        const index = imageList.value.findIndex(img => img.url === filePath)
        if (index !== -1) {
          imageList.value[index].uploading = false
          imageList.value[index].error = true
        }
        
        showError(error.message || '图片上传失败')
        emit('error', error)
        
        return null
      }
    }

    // 选择图片
    const chooseImage = () => {
      const sourceType = []
      if (props.allowCamera) sourceType.push('camera')
      if (props.allowAlbum) sourceType.push('album')

      if (sourceType.length === 0) {
        showError('请至少启用相机或相册功能')
        return
      }

      const count = props.multiple ? props.maxCount - imageList.value.length : 1

      uni.chooseImage({
        count,
        sizeType: ['compressed'],
        sourceType,
        success: async (res) => {
          console.log('选择图片成功:', res)
          console.log('tempFiles:', res.tempFiles)
          console.log('tempFilePaths:', res.tempFilePaths)
          
          // 验证图片
          const validImages = []
          
          // 优先使用tempFilePaths
          if (res.tempFilePaths && res.tempFilePaths.length > 0) {
            for (const tempFilePath of res.tempFilePaths) {
              console.log('处理图片路径:', tempFilePath)
              // 创建一个临时的文件对象用于验证
              const tempFile = { path: tempFilePath }
              const validation = validateImage(tempFile)
              if (validation.valid) {
                validImages.push(tempFilePath)
              } else {
                showError(validation.message)
                return
              }
            }
          } else if (res.tempFiles && res.tempFiles.length > 0) {
            for (const tempFile of res.tempFiles) {
              console.log('处理图片文件:', tempFile)
              const validation = validateImage(tempFile)
              if (validation.valid) {
                // 获取文件路径
                const filePath = tempFile.path || tempFile.tempFilePath
                if (filePath) {
                  validImages.push(filePath)
                } else {
                  showError('无法获取图片路径')
                  return
                }
              } else {
                showError(validation.message)
                return
              }
            }
          } else {
            showError('未获取到图片文件')
            return
          }

          // 处理图片上传
          if (props.autoUpload) {
            // 自动上传模式
            for (const filePath of validImages) {
              await uploadImage(filePath)
            }
          } else {
            // 手动上传模式，只添加到列表
            for (const filePath of validImages) {
              imageList.value.push({
                url: filePath,
                uploading: false,
                error: false
              })
            }
            emit('success', validImages)
          }
          
          clearError()
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
          showError('选择图片失败，请重试')
          emit('error', error)
        }
      })
    }

    // 验证图片
    const validateImage = (file) => {
      console.log('验证图片文件:', file)
      
      // 检查文件大小
      const maxSizeBytes = props.maxSize * 1024 * 1024
      if (file.size && file.size > maxSizeBytes) {
        return {
          valid: false,
          message: `图片大小不能超过${props.maxSize}MB`
        }
      }

      // 检查文件类型 - 多种方式获取文件扩展名
      let extension = ''
      
      // 1. 优先从文件路径获取扩展名
      if (file.path) {
        const pathParts = file.path.split('.')
        if (pathParts.length > 1) {
          extension = pathParts[pathParts.length - 1].toLowerCase()
        }
      }
      
      // 2. 如果路径中没有扩展名，尝试从文件名获取
      if (!extension && file.name) {
        const nameParts = file.name.split('.')
        if (nameParts.length > 1) {
          extension = nameParts[nameParts.length - 1].toLowerCase()
        }
      }
      
      // 3. 如果还是没有扩展名，尝试从URL获取（排除blob URL）
      if (!extension && file.url && !file.url.startsWith('blob:')) {
        const urlParts = file.url.split('.')
        if (urlParts.length > 1) {
          extension = urlParts[urlParts.length - 1].toLowerCase()
        }
      }
      
      // 4. 如果仍然没有扩展名，尝试从MIME类型推断
      if (!extension && file.type) {
        const mimeToExt = {
          'image/jpeg': 'jpg',
          'image/jpg': 'jpg',
          'image/png': 'png',
          'image/gif': 'gif',
          'image/bmp': 'bmp',
          'image/webp': 'webp'
        }
        extension = mimeToExt[file.type] || ''
      }
      
      // 5. 如果还是没有扩展名，尝试从文件内容类型推断
      if (!extension && file.contentType) {
        const mimeToExt = {
          'image/jpeg': 'jpg',
          'image/jpg': 'jpg',
          'image/png': 'png',
          'image/gif': 'gif',
          'image/bmp': 'bmp',
          'image/webp': 'webp'
        }
        extension = mimeToExt[file.contentType] || ''
      }
      
      console.log('文件扩展名:', extension)
      console.log('允许的类型:', props.allowedTypes)
      console.log('文件对象详情:', {
        path: file.path,
        name: file.name,
        url: file.url,
        type: file.type,
        contentType: file.contentType,
        size: file.size
      })
      
      // 如果仍然无法识别格式，但文件大小合理，则允许通过
      if (!extension) {
        // 检查是否是blob URL，如果是则可能是临时文件，允许通过
        if (file.path && (file.path.startsWith('blob:') || file.path.startsWith('http'))) {
          console.log('检测到临时文件或网络文件，允许通过验证')
          return { valid: true }
        }
        
        return {
          valid: false,
          message: '无法识别图片格式，请选择正确的图片文件'
        }
      }
      
      if (!props.allowedTypes.includes(extension)) {
        return {
          valid: false,
          message: `只支持${props.allowedTypes.join('、')}格式的图片，当前文件格式：${extension}`
        }
      }

      return { valid: true }
    }

    // 删除图片
    const removeImage = (index) => {
      const removedImage = imageList.value[index]
      imageList.value.splice(index, 1)
      emit('remove', { index, image: removedImage })
    }

    // 预览图片
    const previewImage = (index) => {
      const urls = imageList.value.map(img => img.url || img)
      uni.previewImage({
        urls,
        current: index,
        success: () => {
          emit('preview', { index, image: imageList.value[index] })
        }
      })
    }

    // 显示错误信息
    const showError = (message) => {
      errorMessage.value = message
      uni.showToast({
        title: message,
        icon: 'none'
      })
    }

    // 清除错误信息
    const clearError = () => {
      errorMessage.value = ''
    }

    // 验证组件
    const validate = () => {
      if (props.required && imageList.value.length === 0) {
        showError('请至少上传一张图片')
        return false
      }
      
      // 检查是否有上传失败的图片
      const hasError = imageList.value.some(img => img.error)
      if (hasError) {
        showError('存在上传失败的图片，请重新上传')
        return false
      }
      
      return true
    }

    // 清空图片
    const clear = () => {
      imageList.value = []
    }

    // 获取图片列表
    const getImageList = () => {
      return [...imageList.value]
    }

    // 获取已上传的图片URL列表
    const getUploadedUrls = () => {
      return imageList.value
        .filter(img => !img.uploading && !img.error)
        .map(img => img.url || img)
    }

    // 暴露方法给父组件
    return {
      imageList,
      errorMessage,
      chooseImage,
      removeImage,
      previewImage,
      validate,
      clear,
      getImageList,
      getUploadedUrls,
      uploadImage
    }
  }
}
</script>

<style lang="scss" scoped>
.app-image-upload {
  width: 100%;
}

/* 上传头部 */
.upload-header {
  margin-bottom: 12px;
  
  .header-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
    
    .title-text {
      font-size: 15px;
      font-weight: 600;
      color: #333;
    }
    
    .required {
      color: #f56c6c;
      font-weight: bold;
    }
  }
  
  .upload-tip {
    font-size: 12px;
    color: #999;
    line-height: 1.4;
  }
}

/* 图片上传区域 */
.image-upload-area {
  .image-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    
    .image-item {
      position: relative;
      aspect-ratio: 1;
      
      .uploaded-image {
        width: 100%;
        height: 100%;
        border-radius: 8px;
        object-fit: cover;
        cursor: pointer;
        transition: transform 0.2s ease;
        
        &:hover {
          transform: scale(1.02);
        }
      }
      
      .delete-btn {
        position: absolute;
        top: -6px;
        right: -6px;
        width: 20px;
        height: 20px;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: background-color 0.2s ease;
        
        &:hover {
          background: rgba(0, 0, 0, 0.8);
        }
      }
      
      .upload-progress {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 8px;
      }
    }
    
    .upload-btn {
      aspect-ratio: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 4px;
      background: #f8f9fa;
      border: 2px dashed #ddd;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s ease;
      
      &:hover {
        border-color: #409eff;
        background: #f0f8ff;
      }
      
      .upload-text {
        font-size: 12px;
        color: #999;
        text-align: center;
      }
    }
  }
}

/* 错误信息 */
.error-message {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 8px;
  
  .error-text {
    font-size: 12px;
    color: #f56c6c;
  }
}

/* 响应式设计 */
@media screen and (max-width: 375px) {
  .image-grid {
    gap: 6px;
    
    .upload-btn {
      .upload-text {
        font-size: 11px;
      }
    }
  }
}

@media screen and (min-width: 414px) {
  .image-grid {
    gap: 10px;
  }
}

/* 自定义网格列数 */
.image-grid.grid-2 {
  grid-template-columns: repeat(2, 1fr);
}

.image-grid.grid-4 {
  grid-template-columns: repeat(4, 1fr);
}

.image-grid.grid-5 {
  grid-template-columns: repeat(5, 1fr);
}
</style>
